/*
 * Created by Wildish on 2016-10-31
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 */

package com.wildish.hybridframework.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wildish.hybridframework.R;
import com.wildish.hybridframework.core.HybridGlobal;
import com.wildish.hybridframework.jsbinding.proxy.HybridProxyManager;
import com.wildish.hybridframework.jsbinding.webview.CustomWebChromeClient;
import com.wildish.hybridframework.jsbinding.webview.CustomWebClient;
import com.wildish.hybridframework.jsbinding.webview.HybridJsGlobal;
import com.wildish.hybridframework.jsbinding.webview.JsHelper;
import com.wildish.hybridframework.jsbinding.webview.WebPageIntent;
import com.wildish.hybridframework.utils.OnCustomClickListener;

import org.apache.commons.lang3.StringUtils;

import java.util.Date;

/**
 * 内容展示Activity
 */
public class WebViewActivity extends Activity {
    public static final String FILE_SCHEME = "file:///android_asset";

    private WebView webView;
    private String webViewTag;
    private WebViewActivity me;
    private Resources res;
    private CustomWebClient webClient;
    private long lastClick = 0;

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        me = this;
        res = getResources();

        setContentView(R.layout.activity_webview);
        webView = (WebView) findViewById(R.id.webView);
        RelativeLayout topbar = (RelativeLayout) findViewById(R.id.rl_topbar);
        ImageButton backward = (ImageButton) findViewById(R.id.ib_backward);
        backward.setOnClickListener(new OnCustomClickListener() {
            @Override
            public void onCustomClick(View v) {
                WebViewActivity.this.finish();
            }
        });

        Intent intent = getIntent();
        if (intent == null) {
            Toast.makeText(me, R.string.msg_webview_nointent, Toast.LENGTH_SHORT).show();
            me.finish();
        } else {
            Bundle params = intent.getExtras();
            boolean showTopbar = params.getBoolean("showTopbar", false);
            if (showTopbar) {
                topbar.setVisibility(View.VISIBLE);
            }
            // 初始化控件
            initWebview();
            // 加载页面
            String defaultUrl = "";
            webViewTag = params.getString("typeTag", WebPageIntent.PAGE_TYPE_DEFAULT);
            switch (webViewTag) {
                case WebPageIntent.PAGE_TYPE_OUTLINK:
                    defaultUrl = params.get("linkurl").toString();
                    TextView tvTitle = (TextView) topbar.findViewById(R.id.tv_title);
                    String title = StringUtils.isBlank(params.getString("title")) ? res.getString(R.string.default_outlink_title) : params.getString("title");
                    tvTitle.setText(title);
                    break;
                case WebPageIntent.PAGE_TYPE_INNERLINK:
                    try {
                        String project = params.getString("project", "demo");
                        String linkPage = new String(Base64.encode(params.get("page").toString().getBytes(), Base64.DEFAULT), "UTF-8");
                        linkPage = linkPage.replace("\n", "");
                        if (params.containsKey("paramsdata")) {
                            String paramsData = new String(Base64.encode(params.get("paramsdata").toString().getBytes(), Base64.DEFAULT), "UTF-8");
                            defaultUrl = String.format("%s/web/%s/main.html?_p=%s&_tick=%s&_a=%s",
                                    FILE_SCHEME,
                                    project,
                                    linkPage,
                                    String.valueOf(new Date().getTime()), paramsData);
                        } else {
                            defaultUrl = String.format("%s/web/%s/main.html?_p=%s&_tick=%s",
                                    FILE_SCHEME,
                                    project,
                                    linkPage,
                                    String.valueOf(new Date().getTime()));
                        }
                    } catch (Exception e) {
                        HybridGlobal.logger.log(e);
                        String project = params.getString("project", "demo");
                        defaultUrl = String.format("%s/web/%s/main.html?_tick=%s",
                                FILE_SCHEME,
                                project,
                                String.valueOf(new Date().getTime()));
                    }
                    break;
                case WebPageIntent.PAGE_TYPE_DEFAULT:
                    String project = params.getString("project", "demo");
                    defaultUrl = String.format("%s/web/%s/main.html?_tick=%s",
                            FILE_SCHEME,
                            project,
                            String.valueOf(new Date().getTime()));
                    break;
            }
            HybridGlobal.logger.log("load page:" + defaultUrl);
            webView.loadUrl(defaultUrl);
            HybridGlobal.addWebViewPage(me, webView, webViewTag);
        }
    }

    private WebView getWebView() {
        return this.webView;
    }

    private String getWebViewTag() {
        return this.webViewTag;
    }

    /**
     * 当webview重新获取焦点时，检测是否需要执行回调函数
     *
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        if (hasFocus) {
            HybridProxyManager.getInstance().onTakeFocus();
        }
    }

    private void initWebview() {
        try {
            webView.getSettings().setDefaultTextEncodingName("utf-8");
            webView.getSettings().setMinimumFontSize(1);
            webView.getSettings().setSupportZoom(false);
            webView.getSettings().setBuiltInZoomControls(false);
            webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
            // 网页缓存
            webView.getSettings().setDomStorageEnabled(true);
            webView.getSettings().setDatabaseEnabled(true);
            webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
            // HTML5 cache
            String cacheDirPath = HybridGlobal.getWebRootCacheFolder().getAbsolutePath();
            webView.getSettings().setDatabasePath(cacheDirPath);
            webView.getSettings().setAppCachePath(cacheDirPath);
            webView.getSettings().setAppCacheEnabled(true);
            // show pic
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                webView.getSettings().setAllowFileAccessFromFileURLs(true);
                webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
            }

            // enable js-binding
            webView.getSettings().setJavaScriptEnabled(true);
            webView.addJavascriptInterface(new HybridJsGlobal(me), "Test");

            webView.setWebChromeClient(new CustomWebChromeClient());
            webClient = new CustomWebClient();
            webView.setWebViewClient(webClient);
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        } catch (Exception e) {
            HybridGlobal.logger.log(e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        HybridGlobal.getInstance().getSoundHelper().releaseAll();
        if (webClient != null) {
            webClient.stopAllDownload();
        }
    }

    @Override
    public void onBackPressed() {
        WebView webView = HybridGlobal.getCurrentWebView();
        if (webView != null) {
            if (webView.canGoBack()) {
                webView.loadUrl(JsHelper.createCallback("backward", "{\"success\": true}"));
            } else {
                int size = HybridGlobal.webViewStack.size();
                if (size > 1) {
                    if (webViewTag.equals(WebPageIntent.PAGE_TYPE_OUTLINK)) {
                        HybridGlobal.webViewStack.pop();
                        me.finish();
                    } else {
                        webView.loadUrl(JsHelper.createCallback("cancel", "{}"));
                    }
                } else {
                    if (System.currentTimeMillis() - lastClick > 2000) {
                        lastClick = System.currentTimeMillis();
                        Toast.makeText(me, "再次点击退出系统", Toast.LENGTH_SHORT).show();
                    } else {
                        HybridGlobal.logger.flushAndExit();
                    }
                }
            }
        } else {
            if (System.currentTimeMillis() - lastClick > 2000) {
                lastClick = System.currentTimeMillis();
                Toast.makeText(me, "再次点击退出系统", Toast.LENGTH_SHORT).show();
            } else {
                HybridGlobal.logger.flushAndExit();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        HybridGlobal.logger.log("WebViewActivity result. requestCode: " + requestCode +", resultCode: " + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        HybridProxyManager.getInstance().onActivityResult(requestCode, resultCode, data);
    }
}
